//@ts-nocheck
import rpc from '@ohos.rpc';
import Extension from '@ohos.app.ability.DriverExtensionAbility';
import { KeyCode } from '@ohos.multimodalInput.keyCode';
import dataStorage from '@ohos.data.storage';
import display from '@ohos.display';
import hilog from '@ohos.hilog';
import testNapi from 'libentry.so'

let defaultIndexMap : Int32Array= new Int32Array(4);

let direction : number = 0;

const STORAGE_KEY = [
    { key: 'key1', default: KeyCode.KEYCODE_SPACE },
    { key: 'key2', default: KeyCode.KEYCODE_ENTER },
    { key: 'key3', default: KeyCode.KEYCODE_BACK },
    { key: 'key4', default: KeyCode.KEYCODE_ESCAPE }]

function GetData():void {
    testNapi.getBoardInput().then(()=>{
        hilog.info(0, 'testTag', 'get kbd input success');
    }).catch(()=>{
        hilog.info(0, 'testTag', 'get kbd input failed');
    })
}
class FirstDriverAbilityStub extends rpc.RemoteObject {
    constructor(des) {
        if (typeof des === 'string') {
            super(des);
        } else {
            return null;
        }
    }
    onRemoteMessageRequest(code: number,
        data: MessageSequence,
        reply: MessageSequence,
        options: MessageOption
    ) {
        console.info(`testtag driver extension onRemoteMessageRequest called ${code}`);
        if (code == 1) {
            let keyIndex = data.readInt();
            let keyValue = data.readInt();
            console.info(`testtag driver extension start setOneButtonMapping key:${keyIndex} val:${keyValue}`);
            testNapi.setOneButtonMapping(keyIndex, keyValue);
            console.info(`testtag driver extension setOneButtonMapping called key:${keyIndex} val:${keyValue}`);
            reply.writeInt(keyIndex);
            return true;
        } else if (code == 2) {
            let direction = data.readInt();
            console.info(`testtag driver start setDirection direction:${direction}`);
            testNapi.setDirection(direction);
            console.info(`testtag driver setDirection called`);
            reply.writeInt(direction);
            return true;
        } else if (code == 3) {
            let type = data.readInt();
            type = (globalThis?.connectStatus ? 1 : 0);
            console.info(`testtag get connection status called status:${type}`);
            reply.writeInt(type);
            return true;
        }
    }

    sendDisconnect() {
        let option = new rpc.MessageOption();
        let dataSend = new rpc.MessageSequence();
        let reply = new rpc.MessageSequence();
        hilog.info(0, 'testTag', `sendDisconnect`);
        sendMessageRequest(0x99, dataSend, reply, option).then((ret) => {
            let msg = reply.readInt();
            reply.writeInt(msg);
            hilog.info(0, 'testTag', `sendDisconnect sendMessageRequest ret:${ret} msg:${msg}`);
        }).catch((error) => {
            hilog.info(0, 'testTag', 'sendDisconnect sendMessageRequest failed');
        });
    }
}

export default class DriverExtAbility extends Extension {
    getKeyMapInfo() {
        let filePath = this.context.filesDir;
        let keyStorage = dataStorage.getStorageSync(filePath + '/keyInfo');
        STORAGE_KEY.forEach((value, index) => {
            defaultIndexMap[index] = keyStorage.getSync(value.key, value.default)
        })
    }

    getDirectionInfo() {
        let filePath = this.context.filesDir;
        let keyStorage = dataStorage.getStorageSync(filePath + '/keyInfo');
        direction = keyStorage.getSync('direction', 0);
    }

    onInit(want): void {
        console.info('DriverAbility OnInit');
        console.info('OnInit deviceId '+ want.parameters["deviceId"]);
        let ret = testNapi.getProductDesc(want.parameters["deviceId"]);
        if (ret != undefined) {
            [globalThis.productDesc, globalThis.productId] = ret;
        }
        this.getKeyMapInfo()
        this.getDirectionInfo()
        // 获取屏幕分辨率
        display.getAllDisplays((err, data:Array<display.Display>) => {
            if (err.code) {
                hilog.error(0, 'testTag','Failed to obtain all the display objects. Code: ' + JSON.stringify(err));
                return;
            }
            hilog.info(0, 'testTag', 'Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(data));
            // 传递给native层
            testNapi.setDisplayInfo(data[0].width, data[0].height);
            testNapi.setButtonMapping(defaultIndexMap);
            testNapi.setDirection(direction);
            GetData();
        });
        globalThis.context = this.context;
    }
    onRelease() :void {
        console.info('DriverAbility onRelease');
        // 释放底层资源
        testNapi.releaseResource();
    }
    onConnect(want): rpc.RemoteObject {
        console.info('DriverAbility onConnect');
        globalThis?.connectStatus = true;
        return new FirstDriverAbilityStub('remote');
    }
    onDisconnect(want): void {
        console.info('DriverAbility onDisconnect');
        globalThis?.connectStatus = false;
    }
    onDump(params): Array<string> {
        console.info('DriverAbility onDump, params:' + JSON.stringify(params));
        return ['params'];
    }
};